package com.fz.us.oa.web.controller.main.company;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.SearchEnum;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.page.PageHelp;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.bean.search.rule.Rule;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.base.utils.EntityConfig;
import com.fz.us.admin.base.utils.EntityUtil;
import com.fz.us.admin.company.entity.*;
import com.fz.us.admin.company.service.*;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import com.google.common.collect.Sets;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 控制器 - 岗位信息
 * ============================================================================
 * 版权所有 2016 。
 *
 * @author fallenpanda
 * @version 1.0 2016-08-09 。
 * ============================================================================
 */
@Controller
@RequestMapping(value = "/main/stepCon")
public class StepConController extends BaseController {


    private static final long serialVersionUID = 1390627493141992856L;

    @Autowired
    private StepBriefService stepBriefService;
    @Autowired
    private StepConService stepConService;



    /**
     * 新建页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model, String parentId, String keyId) {
        StepBrief stepBrief = null;
        StepCon stepCon = null;
        String[] fieldNames = null;
        if (StringUtils.isNotEmpty(parentId)){
            stepBrief = stepBriefService.get(parentId);
            stepCon = new StepCon();
            stepCon.setStepBrief(stepBrief);
        }
        if (StringUtils.isNotEmpty(keyId)){
            stepCon = stepConService.get(keyId);
            stepBrief = stepCon.getStepBrief();
        }
        try {
            Class table =  Class.forName(stepBrief.getProcessBrief().getTableKey());
            fieldNames =  EntityUtil.getFiledName(table);
            // LogUtil.info("fieldNames:"+ fieldNames);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        model.addAttribute("keyId", keyId);
        model.addAttribute("parentId", parentId);
        model.addAttribute("stepCon",stepCon);
        model.addAttribute("stepBrief", stepBrief);
        model.addAttribute("fieldNames", fieldNames);
        return "/main/company/stepCon_input";
    }



    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user, String parentId, String content, String formulaField, String keyId,
                       String formulaFlag,  String stepName, int stepNo, String formulaVal) {
        Map<String,Object> rMap=new HashMap<String,Object>();
        StepBrief stepBrief = null;
        StepCon stepCon = null;
        if(StringUtils.isNotEmpty(keyId)){
            stepCon = stepConService.get(keyId);
        }else{
            stepCon = new StepCon();
            stepCon.setCreater(user);
        }
        if(StringUtils.isNotEmpty(parentId)){
            stepBrief = stepBriefService.get(parentId);
            stepCon.setStepBrief(stepBrief);
        }
        stepCon.setName(stepName);
        stepCon.setContent(content);
        stepCon.setFormulaField(formulaField);
        stepCon.setFormulaFlag(formulaFlag);
        stepCon.setFormulaVal(formulaVal);
        stepCon.setStepNo(stepNo);
        stepCon.setCompany(user.getCompany());
        if(StringUtils.isNotEmpty(keyId)){
            stepConService.update(stepCon);
            rMap.put("message", "更新成功");
        }else{
            stepConService.save(stepCon);
            rMap.put("message","保存成功");
        }

        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }




    /**
     * 操作
     */
    @RequestMapping(value = "delete/{keyId}", method = RequestMethod.POST)
    public Object method(@CurrentUser User user,
                         @PathVariable String keyId) {
        if(StringUtils.isNotEmpty(keyId)){
            StepCon stepCon = stepConService.get(keyId);
            stepCon.setState(BaseEnumManager.StateEnum.Delete);
            stepConService.update(stepCon);
            return ajaxJson(resultService.successWithId(keyId));
        }else{
            return ajaxJson(resultService.fail());
        }
    }

    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters,String parentId) {
        Company company = user.getCompany();
        Order order = null;
        order = Order.order("createTime", SearchEnum.OrderType.asc);
        // 排序
        /*
        Order order = null;
        if (StringUtils.isNotBlank(pager.getSidx()) && StringUtils.isNotBlank(pager.getSord())) {
            order = Order.order(pager.getSidx(), SearchEnum.OrderType.valueOf(pager.getSord()));
        }

        List<Rule> rules = getSearchFilterRules(pager.getSearch(), filters);
        PageHelp.page(pager.getPage(), pager.getRows()), rules, order
        */
        StepBrief stepBrief = null;
        if(StringUtils.isNotEmpty(parentId)){
            stepBrief = stepBriefService.get(parentId);
        }
        SearchResultPaging searchResult = stepConService.pagingStepCon(null,null,order, stepBrief,company, BaseEnumManager.StateEnum.Enable);

        List<StepCon> stepConList = searchResult.getList();

        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(StepCon stepCon: stepConList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",stepCon.getId());
            rMap.put("content", stepCon.getContent());
            rMap.put("name", stepCon.getName());
            rMap.put("creater", stepCon.getCreater() != null ? stepCon.getCreater().getName() : "");
            rMap.put("createTime", DataUtil.DateToString(stepCon.getCreateTime(), "yyyy-MM-dd"));
            rMap.put("formula", stepCon.getFormulaField()+stepCon.getFormulaFlag()+stepCon.getFormulaVal());
            rMap.put("stepNo", stepCon.getStepNo());
            dataRows.add(rMap);
        }

        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());

        return data;
    }





}
